﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using Autofac;
using common;
using i_core;
using i_core.net;
using i_core.usr;

namespace client35 {
	static class Program {
		private static string CurrentVerXMLPath;
		private static string UpdateVerXMLPath;
		private static string CurrentVerStr;
		private static string UpdateVerStr;

		private static i_log log;

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() {
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);



			global_vars.builder = new ContainerBuilder();
			autofac_reg.reg_key<i_log>();

			autofac_reg.reg_interface<i_user_info>();
			autofac_reg.reg_interface<i_account>();
			autofac_reg.reg_key<i_connect>();
			global_vars.scope = global_vars.builder.Build().BeginLifetimeScope();

			log = global_vars.scope.ResolveKeyed<i_log>(log_type.log4net,
							new NamedParameter("user", "system"),
							new NamedParameter("islog", true)
					);
			log.Debug("register interface to builder successful");

			//处理未捕获的异常
			Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
			//处理UI线程异常
			Application.ThreadException += new System.Threading.ThreadExceptionEventHandler((obj, e) => {
				log.Error("Application_ThreadException\r\n" + Environment.StackTrace, e);
			});
			//处理非UI线程异常
			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((obj, e) => {
				log.Error("CurrentDomain_UnhandledException\r\n" + Environment.StackTrace, e);
			});


			var instance = RunningInstance();
			if (instance != null) {
				instance.Kill();
			}

			LoadCurrentVersion();
			LoadUpdateVersion();

			if (CurrentVerStr != UpdateVerStr) {
				log.Debug("检查到有新版本");
				Process.Start("UpdateClient.exe");
				return;
			}



			var login_frm = new login();
			if (login_frm.ShowDialog() == DialogResult.OK)
				Application.Run(new MinChat(login_frm.user_info));
		}
		/// <summary> 
		/// 获取正在运行的实例，没有运行的实例返回null; 
		/// </summary> 
		public static Process RunningInstance() {
			var current = Process.GetCurrentProcess();
			var processes = Process.GetProcessesByName(current.ProcessName);
			foreach (var process in processes) {
				if (process.Id != current.Id) {
					if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName) {
						return process;
					}
				}
			}
			return null;
		}

		private static void LoadCurrentVersion() {
			var AppPath = Application.StartupPath;
			CurrentVerXMLPath = AppPath + "\\info\\UpdateInfo.xml";
			var doc = new XmlDocument();
			try {
				doc.Load(CurrentVerXMLPath);
				CurrentVerStr = doc.GetElementsByTagName("UpdateVersion")[0].Attributes[0].Value;
			} catch (Exception ex) {
				log.Error("获取本程序版本号失败:", ex);
			}
		}

		private static void LoadUpdateVersion() {

			string UpdatePath = $"http://61.162.59.62:7999/Update/Client";
			UpdateVerXMLPath = UpdatePath + "/UpdateInfo.xml";
			var doc = new XmlDocument();
			try {
				var wr = (HttpWebRequest)HttpWebRequest.Create(UpdateVerXMLPath);
				var wrs = (HttpWebResponse)wr.GetResponse();
				var ss = wrs.GetResponseStream();
				doc.Load(ss);
				UpdateVerStr = doc.GetElementsByTagName("UpdateVersion")[0].Attributes[0].Value;

			} catch (Exception ex) {
				log.Error("获取升级程序版本号失败:", ex);
			}
		}
	}
}
